package com.lagou.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class RabbitConfig {

    // ------- Exchange -------
    public static final String EX_PAY = "ex.pay";
    public static final String EX_PAY_EX = "ex.pay.expired";

    // ------- Queue -------
    public static final String Q_PAY = "q.pay";
    public static final String Q_PAY_EX = "q.pay.expired";

    // ------- Routing Key -------
    public static final String RK_PAY = "rk.pay";
    public static final String RK_PAY_EX = "rk.pay.expired";

    @Bean
    public Queue payQueue() {
        Map<String, Object> props = new HashMap<>();
        // 核心思路：消息10s超时后消息自动转移到死信交换器->死信队列，从而实现支付超时功能
        props.put("x-message-ttl", 10000);
        props.put("x-dead-letter-exchange", EX_PAY_EX);
        props.put("x-dead-letter-routing-key", RK_PAY_EX);
        Queue queue = new Queue(Q_PAY, true, false, false, props);
        return queue;
    }

    @Bean
    public Queue expiredPayQueue() {
        Queue queue = new Queue(Q_PAY_EX, true, false, false);
        return queue;
    }

    @Bean
    public Exchange payExchange() {
        return new DirectExchange(EX_PAY, true, false, null);
    }

    @Bean
    public Exchange expiredPayExchange() {
        return new DirectExchange(EX_PAY_EX, true, false, null);
    }

    @Bean
    public Binding payQueueBinding() {
        return BindingBuilder.bind(payQueue()).to(payExchange()).with(RK_PAY).noargs();
    }

    @Bean
    public Binding expiredPayQueueBinding() {
        return BindingBuilder.bind(expiredPayQueue()).to(expiredPayExchange()).with(RK_PAY_EX).noargs();
    }

}
